import cv2

#函数作用:在不损失图片比例的条件下填充至640x640
def padding_img(img_path):
    # 读取图像
    img = cv2.imread(img_path)    
    # 计算缩放比例              
    scale_percent = 640 / img.shape[0]          
    # 计算缩放后的图像大小
    width = int(img.shape[1] * scale_percent)
    height = int(img.shape[0] * scale_percent)
    dim = (width, height)
    # 缩放图像
    resized_img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    #计算像素填充数
    width_pad = 640-width
    #左侧需要的填充
    left_pad = width_pad//2
    #右侧需要的填充
    right_pad = width_pad-left_pad
    #定义填充的颜色
    color = [114,114,114]
    #在左右两侧填充指定的像素
    padded_img = cv2.copyMakeBorder(resized_img, 0, 0, left_pad, right_pad, cv2.BORDER_CONSTANT, value=color)
    print('需要填充的数值',width_pad)
    #保存图片
    save_img = cv2.imwrite('fill_img.jpg',padded_img)
    # #显示原始图像和缩放后的图像
    # cv2.imshow("Original image", img)
    # cv2.imshow("Resized image", resized_img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

if __name__ == "__main__":
    s1 = padding_img('图片的路径')
    
